import 'package:flutter/material.dart';
import 'package:flutter_bilibili/core/extension/int_extension.dart';
import 'package:flutter_bilibili/core/model/video_model.dart';
import 'package:flutter_bilibili/core/viewmodel/video_view_model.dart';
import 'package:flutter_bilibili/ui/pages/home/home_video_item.dart';
import 'package:flutter_bilibili/ui/shared/app_theme.dart';
import 'package:flutter_bilibili/ui/shared/image_assets.dart';
import 'package:flutter_easyrefresh/easy_refresh.dart';
import 'package:flutter_swiper_null_safety/flutter_swiper_null_safety.dart';
import 'package:provider/provider.dart';

import 'home_refresh_item.dart';
import 'load_more_videos_data.dart';

class HYHomeRecommendScreen extends StatefulWidget {
  const HYHomeRecommendScreen({Key? key}) : super(key: key);

  @override
  State<HYHomeRecommendScreen> createState() => _HYHomeRecommendScreenState();
}

class _HYHomeRecommendScreenState extends State<HYHomeRecommendScreen> {
  final List<Widget> _homeRecommendWidgets = [];

  @override
  void initState() {
    super.initState();
  }

  @override
  Widget build(BuildContext context) {
    ///拿到共享数据
    return Consumer<HYVideoViewModel>(
      builder: (ctx, videoVM, child) {
        if (videoVM.videos.isEmpty) {
          ///未加载出数据时显示
          return Center(
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                Container(
                  padding: EdgeInsets.symmetric(horizontal: 40.px),
                  child: Image.asset(ImageAssets.holderLoadingPNG),
                ),
                SizedBox(
                  height: 30.px,
                ),
                TextButton(
                    style: ButtonStyle(
                      backgroundColor:
                          MaterialStateProperty.all(HYAppTheme.norTextColors),
                    ),
                    onPressed: () {
                      setState(() {
                        ///有网络时拉取数据
                        videoVM.updateHYVideoViewModel();
                      });
                    },
                    child: Text(
                      "刷新一下",
                      style: TextStyle(
                          color: Colors.white,
                          fontSize: HYAppTheme.xxSmallFontSize),
                    ))
              ],
            ),
          );
        }

        ///还没有数据就初始化数据
        if (_homeRecommendWidgets.isEmpty) {
          _homeRecommendWidgets.addAll([
            ///前三条视频数据为轮播图数据
            buildHomeRecommendCarousel(videoVM.videos.sublist(0, 3)),

            ///后面的数据用于card
            buildHomeRecommendVideoCards(videoVM.videos.sublist(3)),
          ]);
        }

        ///上拉刷新和下拉加载
        return EasyRefresh(
          onRefresh: () async {
            refreshVideosData(videoVM);

            ///耗时操作放前面,3秒内加载数据
            await Future.delayed(Duration(seconds: 3)).then((value) {
              setState(() {
                ///页码加一，获取下一页的数据
                videoVM.baseDataVM.pn++;

                ///在顶部添加数据
                _homeRecommendWidgets.insert(
                    0, HYHomeRefreshItem(mode: 0, videos: videoVM.videos));
              });
            });
          },
          onLoad: () async {
            loadMoreVideosData(videoVM);
            await Future.delayed(const Duration(seconds: 3)).then((value) {
              setState(() {
                ///页码加一，获取下一页的数据
                videoVM.baseDataVM.pn++;
                _homeRecommendWidgets
                    .add(HYHomeRefreshItem(mode: 1, videos: videoVM.videos));
              });
            });
          },
          child: SingleChildScrollView(
            child: Padding(
              padding: EdgeInsets.only(
                  left: 8.px, right: 8.px, top: 4.px, bottom: 0),
              child: Column(
                children: _homeRecommendWidgets,
              ),
            ),
          ),
        );
      },
    );
  }

  ///轮播图
  Widget buildHomeRecommendCarousel(List<HYVideoModel> data) {
    return ClipRRect(
      borderRadius: BorderRadius.circular(4.px),
      child: Container(
        margin: EdgeInsets.only(bottom: 8.px),
        height: 190.px, //这里的轮播图组件必须包裹在有高度的控件或者设置比例
        child: Swiper(
          itemBuilder: (ctx, index) {
            return Image.network(
              data[index].pic,
              fit: BoxFit.fill,
            );
          },
          itemCount: data.length,
          indicatorLayout: PageIndicatorLayout.SCALE,
          autoplayDelay: 3000,
          pagination: SwiperPagination(
              alignment: Alignment.bottomRight,
              margin:
                  EdgeInsets.only(left: 0, right: 8.px, bottom: 8.px, top: 0)),
          fade: 1.0,
          autoplay: true,
          scrollDirection: Axis.horizontal,
        ),
      ),
    );
  }

  ///card视频
  Widget buildHomeRecommendVideoCards(List<HYVideoModel> data) {
    return GridView.builder(
      /**
       * 这里的shrinkWrap和physics必须设置，
       * 搭配SingleChildScrollView和column一起使用
       */
      shrinkWrap: true,
      physics: const NeverScrollableScrollPhysics(),
      itemCount: data.length,
      gridDelegate: const SliverGridDelegateWithFixedCrossAxisCount(
          crossAxisCount: 2, childAspectRatio: 0.9 //这里的比例设置了，子widget高度属性就无效果了
          ),
      itemBuilder: (ctx, index) {
        return HYHomeVideoItem(video: data[index]);
      },
    );
  }
}
